package com.vehicle.biz.schedule;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import com.vehicle.biz.event.VehicleChangeEvent;
import com.vehicle.domains.bo.QueryCommonVehicleBo;
import com.vehicle.domains.bo.QueryTransportVehicleBo;
import com.vehicle.domains.entity.CommonVehicleEntity;
import com.vehicle.domains.entity.TransportVehicleEntity;
import com.vehicle.enums.GovUploadStatus;
import com.vehicle.service.CommonVehicleService;
import com.vehicle.service.TransportVehicleService;
import jakarta.annotation.Resource;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class TjSchedule {

    @Resource
    private TransportVehicleService transportVehicleService;
    @Resource
    private CommonVehicleService commonVehicleService;
    @Resource
    private ApplicationEventPublisher publisher;
    @Scheduled(fixedRate = 1, timeUnit = TimeUnit.MINUTES)
    public void compensateUploadGovFail() {
        QueryTransportVehicleBo queryTransportVehicleBo = new QueryTransportVehicleBo();
        queryTransportVehicleBo.setStartTime(DateUtil.offset(new Date(), DateField.HOUR,-1));
        queryTransportVehicleBo.setEndTime(DateUtil.offset(new Date(), DateField.MINUTE,-5));
        queryTransportVehicleBo.setGovUploadStatus(GovUploadStatus.needCompensateStatus());

        List<TransportVehicleEntity> transportVehicleEntityList = transportVehicleService.selectTransportVehicleList(queryTransportVehicleBo);
        List<Long> list = transportVehicleEntityList.stream().map(TransportVehicleEntity::getId).toList();

        QueryCommonVehicleBo queryCommonVehicleBo = new QueryCommonVehicleBo();
        queryCommonVehicleBo.setAssIds(list);
        List<CommonVehicleEntity> commonVehicleEntityList = commonVehicleService.selectCommonVehicleList(queryCommonVehicleBo);

        for (CommonVehicleEntity commonVehicleEntity : commonVehicleEntityList) {
            VehicleChangeEvent vehicleChangeEvent = new VehicleChangeEvent(this, commonVehicleEntity.getId());
            publisher.publishEvent(vehicleChangeEvent);
        }

    }
}
